package cn.kgc.jdbc;

import cn.kgc.jdbc.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: mosin
 * @version: v1.0  2022/8/30
 * 演示jdbc数据操作时的事务处理
 * 转账业务
 * 事务: 完成一次业务操作需要执行的sql语句，sql语句要么全部成功要么全部失败
 *
 * jdbc的事务默认自动提交
 */
public class TestTransaction {

    public static void main(String[] args) {

        QueryRunner queryRunner = new QueryRunner();
        // 通过连接 手动控制事务
        Connection connection = DruidUtil.getConnection();
        try {
            connection.setAutoCommit(false);
            // 1001  -> 1002  100
            String sql ="update account set money = money + ? where account = ?";
            int update = queryRunner.update(connection,sql, -100, "1001");
            System.out.println(update);

            int i = 1/0;

            update = queryRunner.update(connection,sql, 100, "1002");
            System.out.println("update = " + update);
            //  以上两条sql语句全部执行成功  手动提交事务
            connection.commit();
        } catch (Exception throwables) {
            System.out.println("被抓取异常");
            try {
                //设置事务的回滚
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }

    }
}
